package com.news.service.impl;

import com.news.model.NewsItem;
import com.news.model.NewsSource;
import com.news.service.NewsDetailService;
import com.news.util.HttpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 新闻详情服务实现
 */
public class NewsDetailServiceImpl implements NewsDetailService {
    
    private static final Logger logger = LoggerFactory.getLogger(NewsDetailServiceImpl.class);
    
    @Override
    public NewsItem getNewsDetail(NewsItem newsItem) {
        if (newsItem == null) {
            return null;
        }
        
        try {
            // 根据新闻来源获取详细内容
            String source = newsItem.getSource();
            
            if (source.contains("百度") || source.contains("baidu")) {
                return getBaiduNewsDetail(newsItem);
            } else if (source.contains("哔哩哔哩") || source.contains("bilibili")) {
                return getBilibiliNewsDetail(newsItem);
            } else {
                return getGeneralNewsDetail(newsItem);
            }
            
        } catch (Exception e) {
            logger.error("获取新闻详情失败: {}", newsItem.getTitle(), e);
            return newsItem; // 返回原始新闻项
        }
    }
    
    @Override
    public boolean isDetailSupported(NewsItem newsItem) {
        return newsItem != null && newsItem.getUrl() != null && !newsItem.getUrl().trim().isEmpty();
    }
    
    /**
     * 获取百度新闻详情
     */
    private NewsItem getBaiduNewsDetail(NewsItem newsItem) {
        try {
            String title = newsItem.getTitle();
            String searchUrl = "https://www.baidu.com/s?wd=" + URLEncoder.encode(title, StandardCharsets.UTF_8.toString());
            
            String html = HttpUtil.get(searchUrl);
            Document doc = Jsoup.parse(html);
            
            // 查找搜索结果
            Elements results = doc.select(".result.c-container");
            
            StringBuilder detailContent = new StringBuilder();
            detailContent.append("【百度热搜详情】\n\n");
            detailContent.append("标题: ").append(title).append("\n\n");
            
            // 获取相关新闻和描述
            int count = 0;
            for (Element result : results) {
                if (count >= 3) break; // 只取前3个结果
                
                try {
                    Element titleElement = result.select("h3 a").first();
                    Element abstractElement = result.select(".c-abstract").first();
                    
                    if (titleElement != null) {
                        String resultTitle = titleElement.text().trim();
                        String resultUrl = titleElement.attr("href");
                        String resultAbstract = abstractElement != null ? abstractElement.text().trim() : "";
                        
                        if (!resultTitle.isEmpty()) {
                            detailContent.append("相关新闻 ").append(count + 1).append(":\n");
                            detailContent.append("标题: ").append(resultTitle).append("\n");
                            if (!resultAbstract.isEmpty()) {
                                detailContent.append("摘要: ").append(resultAbstract).append("\n");
                            }
                            detailContent.append("链接: ").append(resultUrl).append("\n\n");
                            count++;
                        }
                    }
                } catch (Exception e) {
                    logger.warn("解析搜索结果失败", e);
                }
            }
            
            // 尝试获取百度百科信息
            Elements baikeResults = doc.select(".c-container[srcid*='baike']");
            if (!baikeResults.isEmpty()) {
                try {
                    Element baikeElement = baikeResults.first();
                    Element baikeDesc = baikeElement.select(".c-abstract").first();
                    if (baikeDesc != null) {
                        detailContent.append("百度百科:\n");
                        detailContent.append(baikeDesc.text().trim()).append("\n\n");
                    }
                } catch (Exception e) {
                    logger.warn("解析百科信息失败", e);
                }
            }
            
            if (detailContent.length() > 100) {
                NewsItem detailItem = new NewsItem();
                detailItem.setTitle(newsItem.getTitle());
                detailItem.setContent(detailContent.toString());
                detailItem.setSource(newsItem.getSource());
                detailItem.setUrl(searchUrl);
                detailItem.setPublishTime(newsItem.getPublishTime());
                detailItem.setCategory(newsItem.getCategory());
                detailItem.setHotScore(newsItem.getHotScore());
                detailItem.setAuthor(newsItem.getAuthor());
                
                return detailItem;
            }
            
        } catch (Exception e) {
            logger.error("获取百度新闻详情失败", e);
        }
        
        return newsItem;
    }
    
    /**
     * 获取B站新闻详情
     */
    private NewsItem getBilibiliNewsDetail(NewsItem newsItem) {
        try {
            String url = newsItem.getUrl();
            if (url == null || url.trim().isEmpty()) {
                return newsItem;
            }
            
            String html = HttpUtil.get(url);
            Document doc = Jsoup.parse(html);
            
            StringBuilder detailContent = new StringBuilder();
            detailContent.append("【B站内容详情】\n\n");
            detailContent.append("标题: ").append(newsItem.getTitle()).append("\n\n");
            
            // 尝试获取视频描述
            Element descElement = doc.select(".video-desc").first();
            if (descElement != null) {
                detailContent.append("视频描述:\n");
                detailContent.append(descElement.text().trim()).append("\n\n");
            }
            
            // 尝试获取UP主信息
            Element upElement = doc.select(".up-name").first();
            if (upElement != null) {
                detailContent.append("UP主: ").append(upElement.text().trim()).append("\n\n");
            }
            
            // 尝试获取视频数据
            Elements statsElements = doc.select(".video-data span");
            if (!statsElements.isEmpty()) {
                detailContent.append("视频数据:\n");
                for (Element stat : statsElements) {
                    String statText = stat.text().trim();
                    if (!statText.isEmpty()) {
                        detailContent.append("- ").append(statText).append("\n");
                    }
                }
                detailContent.append("\n");
            }
            
            if (detailContent.length() > 100) {
                NewsItem detailItem = new NewsItem();
                detailItem.setTitle(newsItem.getTitle());
                detailItem.setContent(detailContent.toString());
                detailItem.setSource(newsItem.getSource());
                detailItem.setUrl(newsItem.getUrl());
                detailItem.setPublishTime(newsItem.getPublishTime());
                detailItem.setCategory(newsItem.getCategory());
                detailItem.setHotScore(newsItem.getHotScore());
                detailItem.setAuthor(newsItem.getAuthor());
                
                return detailItem;
            }
            
        } catch (Exception e) {
            logger.error("获取B站详情失败", e);
        }
        
        return newsItem;
    }
    
    /**
     * 获取通用新闻详情
     */
    private NewsItem getGeneralNewsDetail(NewsItem newsItem) {
        try {
            String url = newsItem.getUrl();
            if (url == null || url.trim().isEmpty()) {
                return newsItem;
            }
            
            String html = HttpUtil.get(url);
            Document doc = Jsoup.parse(html);
            
            StringBuilder detailContent = new StringBuilder();
            detailContent.append("【新闻详情】\n\n");
            detailContent.append("标题: ").append(newsItem.getTitle()).append("\n\n");
            
            // 尝试获取页面标题
            Element titleElement = doc.select("title").first();
            if (titleElement != null) {
                detailContent.append("页面标题: ").append(titleElement.text().trim()).append("\n\n");
            }
            
            // 尝试获取meta描述
            Element metaDesc = doc.select("meta[name=description]").first();
            if (metaDesc != null) {
                String description = metaDesc.attr("content");
                if (!description.trim().isEmpty()) {
                    detailContent.append("描述: ").append(description.trim()).append("\n\n");
                }
            }
            
            // 尝试获取正文内容
            Elements contentElements = doc.select("p, .content, .article-content, .news-content");
            if (!contentElements.isEmpty()) {
                detailContent.append("正文内容:\n");
                int paragraphCount = 0;
                for (Element p : contentElements) {
                    if (paragraphCount >= 5) break; // 只取前5段
                    
                    String text = p.text().trim();
                    if (text.length() > 20) { // 过滤掉太短的段落
                        detailContent.append(text).append("\n\n");
                        paragraphCount++;
                    }
                }
            }
            
            if (detailContent.length() > 150) {
                NewsItem detailItem = new NewsItem();
                detailItem.setTitle(newsItem.getTitle());
                detailItem.setContent(detailContent.toString());
                detailItem.setSource(newsItem.getSource());
                detailItem.setUrl(newsItem.getUrl());
                detailItem.setPublishTime(newsItem.getPublishTime());
                detailItem.setCategory(newsItem.getCategory());
                detailItem.setHotScore(newsItem.getHotScore());
                detailItem.setAuthor(newsItem.getAuthor());
                
                return detailItem;
            }
            
        } catch (Exception e) {
            logger.error("获取通用新闻详情失败", e);
        }
        
        return newsItem;
    }
} 